<template>
  <page>
    <div slot="body">
      <div class="table-operation">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="openDialogHandle('Add', null)"
        >
          添加角色
        </el-button>
      </div>
      <el-table :data="tableData" border>
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="50px"
        ></el-table-column>
        <el-table-column
          prop="id"
          label="角色ID"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="角色名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="bindUsers"
          label="关联账号数"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" align="center" width="180px">
          <template slot-scope="scope">
            <el-link
              type="primary"
              :underline="false"
              @click="openDialogHandle('Edit', scope.row)"
              >编辑</el-link
            >
            <el-link
              type="primary"
              :underline="false"
              @click="editRole(scope.row)"
              >编辑权限</el-link
            >
            <el-link
              type="primary"
              :underline="false"
              @click="deleteHandle(scope.row)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div slot="footer">
      <el-pagination
        background
        :page-size="pageVO.pageSize"
        :current-page.sync="pageVO.pageNum"
        :total="pageVO.total"
        :layout="pageOptions.layout"
        :page-sizes="pageOptions.pageSizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      :visible.sync="open"
      width="800px"
      @close="closeHandle"
      custom-class="dialog"
      title="编辑权限"
    >
      <div class="top">
        <!-- <el-tag class="info" :key="roles.name" type="info">
          {{ roles.name }}
        </el-tag> -->
        <el-input v-model="roles.name" disabled></el-input>
      </div>
      <el-tree
          class="tree-border"
          :data="menuList"
          show-checkbox
          ref="menu"
          node-key="id"
          :check-strictly="false"
          empty-text="加载中，请稍候"
          :props="defaultProps"
        ></el-tree>
      <!-- <div class="table">
        <div class="head">
          <div class="title" style="width: calc(100% - 200px)">业务模块</div>
          <div class="title">页面权限</div>
        </div>
        <div class="head">
          <div class="all">全部</div>
          <div class="all">
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >
          </div>
        </div>

        <el-table
          ref="table"
          :data="menuList"
          style="width: 100%"
          height="500"
          @selection-change="handleSelectionChange"
          @select="checkSelect"
          row-key="id"
          border
          default-expand-all
          :tree-props="{ children: 'children' }"
        >
          <el-table-column prop="menuName" label="全部" minWidth="200">
          </el-table-column>
          <el-table-column prop="选择" type="selection" width="200">
          </el-table-column>
        </el-table>
      </div> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeHandle" size="small">取 消</el-button>
        <el-button type="primary" @click="submitForm" size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <role-dialog ref="dialogRef" @getList="getTableData(1)" />
  </page>
</template>

<script>
import { delRole } from "../../../api/role";
import pageQuery from "../../mixins/pageQuery";
import roleDialog from "./roleDialog.vue";
import { getList, getMenu, editMenu, getRoleMenu } from "@/api/role";
export default {
  mixins: [pageQuery],
  components: { roleDialog },
  data() {
    return {
      tableData: [],
      menuList: [],
      open: false,
      roles: "",
      isIndeterminate: false,
      checkAll: false,
      pageVO: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
      defaultProps: {
        children: "children",
        label: "menuName",
      },
      grantMenuList: [],
      menuIdList: [],
      checkedCities: [],
    };
  },
  created() {
    this.getTableData(1);
  },
  methods: {
    getTableData() {
      const { projectId } = this.$store.getters;
      const parmas = {
        projectId: projectId,
        pageNo: this.pageVO.pageNum,
        pageSize: this.pageVO.pageSize,
      };
      getList(parmas).then((res) => {
        this.tableData = res.data.data;
        this.pageVO.total = res.data.total;
      });
      getMenu().then((res) => {
        this.menuList = res.data;
        console.log("res", res.data);
      });
    },
    deleteHandle(row) {
      this.$confirm('是否确认删除角色为"' + row.name + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delRole(row.id);
        })
        .then(() => {
          this.getTableData();
          this.$message.success("删除成功");
        });
    },
    closeHandle() {
      this.open = false;
      this.menuIdList = [];
      this.$refs.table.clearSelection();
    },
    async getRoleMenu(row) {
      const { data } = (await getRoleMenu({ roleId: row.id })) || {};
      this.grantMenuList = data || [];
      let checkedKeys = data;
      checkedKeys.forEach((v) => {
        this.$nextTick(() => {
          this.$refs.menu.setChecked(v, true, false);
        });
      });
      // let allList = [];
      // this.getChildMenu(this.menuList, allList);
      // const selectedMenu =
      //   allList.filter((item) => {
      //     return this.grantMenuList.some((grantMenu) => {
      //       return item.id === grantMenu;
      //     });
      //   }) || [];
      // selectedMenu.forEach((item) => {
      //   item.isPush = true;
      //   this.$refs.table.toggleRowSelection(item, true);
      // });
    },
    getChildMenu(menuArr, list = []) {
      for (let menu of menuArr) {
        list.push(menu);
        if (menu.children && menu.children.length > 0) {
          this.getChildMenu(menu.children, list);
        }
      }
    },
    editRole(row) {
      this.open = true;
      this.roles = row;
      this.getRoleMenu(row);
      console.log("rows", row);
    },
    handleSelectionChange(val) {
      this.menuIdList = [];
      val.map((item) => {
        this.menuIdList.push(item.id);
      });
    },
    submitForm() {
      const parmas = {
        menuId: this.getMenuAllCheckedKeys(),
        roleId: this.roles.id,
      };
      editMenu(parmas).then((res) => {
        this.open = false;
        this.$message.success("编辑菜单权限成功");
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    checkSelect(data, row) {
      row.isPush = row.isPush ? 0 : 1;
      if (row.children) {
        this.checkFun(row.children, row.isPush);
      }
      if (row.isPush) {
        this.CheckParentFun(this.menuList, row.parentId);
      } else {
        this.clearParentFun(this.menuList, row.parentId);
      }
      this.fileTreeArr = [];
      this.getId(this.menuList);
    },
    // 子节点全部取消父节点清空
    clearParentFun(table, parentId) {
      table.forEach((element) => {
        if (parentId == element.id) {
          let issel = false;
          element.children.forEach((elementb) => {
            if (elementb.isPush == true) {
              issel = true;
            }
          });
          element.isPush = issel ? 1 : 0;
          if (!issel) {
            this.$refs.table.toggleRowSelection(element, false);
          }
          if (element.parentId) {
            this.clearParentFun(this.menuIdList, element.parentId);
          }
        } else {
          if (element.children) {
            this.clearParentFun(element.children, parentId);
          }
        }
      });
    },
    // 递归选中
    checkFun(data, status) {
      data.forEach((element) => {
        element.isPush = status;
        this.$refs.table.toggleRowSelection(
          element,
          element.isPush ? true : false
        );
        if (element.children) {
          this.checkFun(element.children, element.isPush);
        }
      });
    },
    // 父节点选中
    CheckParentFun(table, parentId) {
      table.forEach((element) => {
        if (parentId == element.id) {
          element.isPush = 1;
          this.$refs.table.toggleRowSelection(element, true);
          if (element.parentId) {
            this.CheckParentFun(this.menuIdList, element.parentId);
          }
        } else {
          if (element.children) {
            this.CheckParentFun(element.children, parentId);
          }
        }
      });
    },
    // 获取选中ID
    getId(data) {
      data.forEach((element) => {
        if (element.isPush) {
          this.fileTreeArr.push(element);
        }
        if (element.children) {
          this.getId(element.children);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.top {
  position: relative;
}
.info {
  position: absolute;
  z-index: 99;
  top: 3px;
  left: 5px;
}
.table {
  margin-top: 20px;
}
.head {
  display: flex;
  justify-content: flex-start;
}
.title {
  padding: 10px;
  width: 200px;
  background-color: #e2eefd;
}
.all {
  padding: 10px;
  width: 200px;
}
.tree-border {
    margin-top: 5px;
    border: 1px solid #e5e6e7;
    background: #fff none;
    border-radius: 4px;
}
</style>
